package com.younion.action.consumer.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.younion.action.consumer.AbstractRequestConsumer;
import com.younion.action.interactive.mobile.ApiConstant;
import com.younion.action.interactive.mobile.ResultObject;
import com.younion.business.IMessageService;
import com.younion.common.constants.MsgStatus;
import com.younion.model.AndroidPushResult;
import com.younion.util.HttpRequestUtils;
import com.younion.util.JsonUtils;
import com.younion.vo.MessageVO;

public class AndroidPushConsumer extends AbstractRequestConsumer {
	private IMessageService messageService = null;
	
	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return addDevice(request, response);
	}

	public void setMessageService(IMessageService messageService) {
		this.messageService = messageService;
	}

	public String addDevice(HttpServletRequest request,
			HttpServletResponse response) {
		List<AndroidPushResult> androidPushResultList = new ArrayList<AndroidPushResult>();
		String userToken = request.getParameter("user_token");
		Map paramMap = new HashMap();
		paramMap.put("usertoken", userToken);
		paramMap.put("status", MsgStatus.UNSEND.getName());
		paramMap.put("ltsendTime", new Date());
		ResultObject resultObject = new ResultObject();
		try {
			List<MessageVO> messageList = messageService.getByMap(paramMap);
			if(messageList!=null&&!messageList.isEmpty()){
				for(MessageVO messageVO : messageList){
					AndroidPushResult androidPushResult = new AndroidPushResult();
					androidPushResult.setId(messageVO.getId().toString());
					androidPushResult.setMessage(messageVO.getContent());
					messageVO.setStatus(MsgStatus.SENDED.getName());
					messageService.save(messageVO);
					androidPushResultList.add(androidPushResult);
				}
			}
			resultObject.setStatus(ApiConstant.SUCCESS_STATUS);
		} catch (Exception e) {
			resultObject.setStatus(ApiConstant.FALSE_STATUS);
			resultObject.setMsg(ApiConstant.PUBLIC_EXCEPTION);
			e.printStackTrace();
		}
		resultObject.setResult(androidPushResultList);
		HttpRequestUtils.printContent(JsonUtils.parseObj2Json(resultObject),
				response);
		return null;
	}
}
